﻿var TableName = "tb_task";
$(function () {

    var oTable = new TableInit();
    oTable.Init();

    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    $("#btn_query").click(function () {
        TableRefresh("#" + TableName);
    })
    $("#btn_clear").click(function () {
        ValueReset(["#search_datepicker input[name='start']", "#search_datepicker input[name='end']"]);
        TableRefresh("#" + TableName);
    })

    $('#add_form').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            add_taskforuser: {
                validators: {
                    notEmpty: {
                        message: '指派任务为必填项'
                    }
                }
            },
            add_TaskInfo: {
                validators: {
                    notEmpty: {
                        message: '任务内容为必填项'
                    }
                }
            }
        }
    });
    $('#edit_form').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            edit_taskforuser: {
                validators: {
                    notEmpty: {
                        message: '指派任务为必填项'
                    }
                }
            },
            edit_TaskInfo: {
                validators: {
                    notEmpty: {
                        message: '任务内容为必填项'
                    }
                }
            }
        }
    });
    InitSelect();
});

var TableInit = function () {
    var oTableInit = new Object();

    oTableInit.Init = function () {
        $('#' + TableName).bootstrapTable({
            url: '../ashx/Task.ashx',
            method: 'get',
            toolbar: '#toolbar',
            striped: true,
            cache: false,
            pagination: true,
            sortable: true,
            sortName: "EndDate",
            sortOrder: "desc",
            queryParams: oTableInit.queryParams,
            sidePagination: "client",
            pageNumber: 1,
            //singleSelect: true,
            pageSize: 10,
            pageList: [10, 25, 50, 100],
            search: true,
            strictSearch: false,
            showColumns: true,
            showRefresh: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            //height: 500, 
            uniqueId: "TaskID",
            showToggle: true,
            cardView: false,
            detailView: false,
            showExport: true,
            buttonsAlign: "right",
            exportTypes: ['excel'],
            Icons: 'glyphicon-export',
            exportOptions: {
                ignoreColumn: [0],
                fileName: '我的任务清单',
                worksheetName: 'sheet1',
                tableName: '我的任务清单',
                excelstyles: ['background-color', 'color', 'font-size', 'font-weight']
            },
            columns: [{
                checkbox: true
            }, {
                field: 'TaskID',
                title: '任务ID',
                visible: false
            }, {
                field: 'UserID',
                title: '任务执行人ID',
                visible: false
            }, {
                field: 'UserName',
                title: '姓名'
            }, {
                field: 'StartDate',
                title: '开始日期',
                formatter: function (value, row, index) {
                    var temp = row.StartDate;
                    return DateFormatter(temp);
                }
            }, {
                field: 'EndDate',
                title: '结束日期',
                formatter: function (value, row, index) {
                    var temp = row.EndDate;
                    return DateFormatter(temp);
                }
            }, {
                field: '',
                title: '工时(天)',
                formatter: function (value, row, index) {
                    return GetDateSubtract(row.StartDate, row.EndDate) + 1;
                }
            }, {
                field: 'TaskInfo',
                title: '工作内容'
            }, {
                field: 'Remark',
                title: '备注'
            }, {
                field: 'CreateTime',
                title: '创建时间',
                formatter: function (value, row, index) {
                    var val = row.CreateTime;
                    if (IsNullOrEmpty(val)) {
                        return val;
                    } else {
                        return val + "<span style='color:gray;'><small> (" + DateTimeFromNow(val) + ")</small></span>";
                    }
                }
            }]
        });
    };

    oTableInit.queryParams = function (params) {
        var temp = {
            action: "GetAllTaskByUserID",
            startDate: $("#search_datepicker input[name='start']").val(),
            endDate: $("#search_datepicker input[name='end']").val()
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        $("#btn_add").click(function () {
            ValueReset(["#add_datepicker input[name='start']", "#add_datepicker input[name='end']", "#add_taskforuser", "add_TaskInfo", "#add_Remark"]);
            $("#Modal_add").modal("show");
            ResetForm("#add_form", true);
        })
        $("#btn_edit").click(function () {
            var rows = GetTableSelections("#" + TableName);
            if (rows.length != 1) {
                ShowMsg("请选择一条需要修改的数据");
                return;
            } else {
                $("#edit_taskid").val(rows[0].TaskID);
                $("#edit_datepicker input[name='start']").val(rows[0].StartDate.substr(0, 10));
                $("#edit_datepicker input[name='end']").val(rows[0].EndDate.substr(0, 10));
                $("#edit_taskforuser").val(rows[0].UserID);
                $("#edit_TaskInfo").val(rows[0].TaskInfo);
                $("#edit_Remark").val(rows[0].Remark);
                $("#Modal_edit").modal("show");
                ResetForm("#edit_form", false);
            }
        })
        $("#btn_delete").click(function () {
            var rows = GetTableSelections("#" + TableName);
            if (rows.length == 0) {
                ShowMsg("请选择要删除的数据！");
                return;
            } else {
                var IDsArray = new Array();
                rows.forEach(function (row) {
                    IDsArray.push(row.TaskID);
                })
                $.ajax({
                    url: '../ashx/Task.ashx',
                    data: { action: "DelTask", IDs: "'" + IDsArray.join("','") + "'" },
                    success: function (r) {
                        var ret = JSON.parse(r);
                        if (ret.code == 0) {
                            ShowMsg(ret.info);
                            TableRefresh("#" + TableName);
                        } else {
                            ShowMsg(ret.info, "error");
                        }
                    }
                });
            }
        })
    };
    return oInit;
};

function add_save() {
    if (!FormIsValid("#add_form")) {
        ShowMsg("表单验证不通过");
        return;
    }
    var obj = new Object();
    obj.StartDate = $("#add_datepicker input[name='start']").val();
    obj.EndDate = $("#add_datepicker input[name='end']").val();
    obj.UserID = $("#add_taskforuser").val();
    obj.TaskInfo = $("#add_TaskInfo").val();
    obj.Remark = $("#add_Remark").val()
    //console.dir(obj);
    $.ajax({
        url: '../ashx/Task.ashx?action=AddTask',
        data: { json: JSONFormat(obj, false) },
        success: function (r) {
            var ret = JSON.parse(r);
            if (ret.code == 0) {
                ShowMsg(ret.info, "success");
                TableRefresh("#" + TableName);
                $("#Modal_add").modal("hide");
            } else {
                ShowMsg(ret.info, "error");
            }
        }
    });
}
function edit_save() {
    if (!FormIsValid("#edit_form")) {
        ShowMsg("表单验证不通过");
        return;
    }
    var obj = new Object();
    obj.TaskID = $("#edit_taskid").val();
    obj.StartDate = $("#edit_datepicker input[name='start']").val();
    obj.EndDate = $("#edit_datepicker input[name='end']").val();
    obj.UserID = $("#edit_taskforuser").val();
    obj.TaskInfo = $("#edit_TaskInfo").val();
    obj.Remark = $("#edit_Remark").val();
    console.dir(obj);
    $.ajax({
        url: '../ashx/Task.ashx?action=ModifyTask',
        data: { json: JSONFormat(obj, false) },
        success: function (r) {
            var ret = JSON.parse(r);
            if (ret.code == 0) {
                ShowMsg(ret.info, "success");
                TableRefresh("#" + TableName);
                $("#Modal_edit").modal("hide");
            } else {
                ShowMsg(ret.info, "error");
            }
        }
    });
}

function DateFormatter(date) {
    if (IsNullOrEmpty(date)) {
        return date;
    }
    var color = "green";
    if (GetDateSubtractFromNow(date) > 0) {
        color = "red";
    }
    if (date.length != 0) {
        return "<span style='color:" + color + ";'>" + date.substr(0, 10) + "</span>";
    } else {
        return temp;
    }
}

function InitSelect() {
    var html = "";
    $.ajax({
        url: '../ashx/Common.ashx',
        data: { action: "GetUsers" },
        success: function (r) {
            var ret = JSON.parse(r);
            ret.forEach(function (u, index) {
                html += "<option value='" + u.UserID + "'>" + u.UserName + "</option>";
            })
            $("#add_taskforuser").html(html);
            $("#edit_taskforuser").html(html);
        }
    });
}